package com.example.text.diyviews



import android.app.Activity
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.graphics.Rect
import android.os.Build
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import java.util.Timer
import java.util.TimerTask

object KeyBoardUtil {

    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    fun showInput(et: EditText, activity: Activity) {
        et.apply {
            isFocusable = true
            isFocusableInTouchMode = true
            requestFocus()
        }

        Timer().schedule(object : TimerTask() {
            override fun run() {
                val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(et, 0)
                et.setSelection(et.text?.length ?: 0)
            }
        }, 500)
    }

    /**
     * 隐藏键盘
     */
    fun hideInput(activity: Activity) {
        if (activity.window.attributes.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            activity.currentFocus?.let {
                val imm = activity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                val v = activity.window.peekDecorView()
                if (v != null) {
                    imm.hideSoftInputFromWindow(v.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            }
        }
    }

    interface OnKeyboardVisibilityListener {
        fun onVisibilityChanged(visible: Boolean)
    }

    /**
     * 监听键盘弹出状态
     */
    fun setKeyboardVisibilityListener(
        activity: Activity,
        listener: OnKeyboardVisibilityListener
    ) {
        val parentView = (activity.findViewById<ViewGroup>(android.R.id.content)).getChildAt(0)
        parentView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {

            private var alreadyOpen = false
            private val defaultKeyboardHeightDP = 100
            private val estimatedKeyboardDP = defaultKeyboardHeightDP +
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 48 else 0
            private val rect = Rect()

            override fun onGlobalLayout() {
                val estimatedKeyboardHeight = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    estimatedKeyboardDP.toFloat(),
                    parentView.resources.displayMetrics
                ).toInt()

                parentView.getWindowVisibleDisplayFrame(rect)
                val heightDiff = parentView.rootView.height - (rect.bottom - rect.top)
                val isShown = heightDiff >= estimatedKeyboardHeight

                if (isShown == alreadyOpen) {
                    Log.i("Keyboard state", "Ignoring global layout change...")
                    return
                }
                alreadyOpen = isShown
                listener.onVisibilityChanged(isShown)
            }
        })
    }
}